'use client'

import { useState, useEffect } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Skeleton } from '@/components/ui/skeleton'
import { 
  ArrowLeft, 
  User, 
  Calendar, 
  Clock, 
  Bug, 
  MessageSquare,
  Paperclip,
  Edit,
  Trash2,
  AlertCircle,
  MoreHorizontal,
  AlertTriangle,
  CheckCircle,
  XCircle
} from 'lucide-react'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'

interface BugDetail {
  id: string
  title: string
  description?: string
  severity: string
  priority: string
  status: string
  dueDate?: string
  resolvedAt?: string
  createdAt: string
  updatedAt: string
  project: {
    id: string
    name: string
    key: string
  }
  iteration?: {
    id: string
    name: string
  }
  requirement?: {
    id: string
    title: string
    type: string
  }
  creator: {
    id: string
    name?: string
    username: string
    email?: string
  }
  assignee?: {
    id: string
    name?: string
    username: string
    email?: string
  }
  comments: Array<{
    id: string
    content: string
    author: {
      name?: string
      username: string
    }
    createdAt: string
  }>
  attachments: Array<{
    id: string
    filename: string
    size: number
    mimeType: string
    createdAt: string
  }>
  _count: {
    comments: number
    attachments: number
  }
}

export function BugDetail() {
  const params = useParams()
  const router = useRouter()
  const bugId = params.id as string
  const [bug, setBug] = useState<BugDetail | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (bugId) {
      fetchBugDetail()
    }
  }, [bugId])

  const fetchBugDetail = async () => {
    setLoading(true)
    try {
      const response = await fetch(`/api/bugs/${bugId}`)
      if (response.ok) {
        const data = await response.json()
        setBug(data)
      } else {
        console.error('Error fetching bug detail')
        router.push('/bugs')
      }
    } catch (error) {
      console.error('Error fetching bug detail:', error)
      router.push('/bugs')
    } finally {
      setLoading(false)
    }
  }

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      open: 'bg-red-100 text-red-800',
      in_progress: 'bg-yellow-100 text-yellow-800',
      resolved: 'bg-green-100 text-green-800',
      closed: 'bg-gray-100 text-gray-800',
      reopened: 'bg-orange-100 text-orange-800'
    }
    return colors[status] || 'bg-gray-100 text-gray-800'
  }

  const getPriorityColor = (priority: string) => {
    const colors: Record<string, string> = {
      low: 'bg-gray-100 text-gray-800',
      medium: 'bg-yellow-100 text-yellow-800',
      high: 'bg-orange-100 text-orange-800',
      urgent: 'bg-red-100 text-red-800'
    }
    return colors[priority] || 'bg-gray-100 text-gray-800'
  }

  const getSeverityColor = (severity: string) => {
    const colors: Record<string, string> = {
      LOW: 'bg-gray-100 text-gray-800',
      MEDIUM: 'bg-yellow-100 text-yellow-800',
      HIGH: 'bg-orange-100 text-orange-800',
      CRITICAL: 'bg-red-100 text-red-800',
      BLOCKER: 'bg-purple-100 text-purple-800'
    }
    return colors[severity] || 'bg-gray-100 text-gray-800'
  }

  const getStatusLabel = (status: string) => {
    const labels: Record<string, string> = {
      open: '待处理',
      in_progress: '处理中',
      resolved: '已解决',
      closed: '已关闭',
      reopened: '已重新打开'
    }
    return labels[status] || status
  }

  const getSeverityLabel = (severity: string) => {
    const labels: Record<string, string> = {
      LOW: '低',
      MEDIUM: '中',
      HIGH: '高',
      CRITICAL: '严重',
      BLOCKER: '阻塞'
    }
    return labels[severity] || severity
  }

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'open':
        return <AlertCircle className="h-4 w-4" />
      case 'in_progress':
        return <AlertTriangle className="h-4 w-4" />
      case 'resolved':
        return <CheckCircle className="h-4 w-4" />
      case 'closed':
        return <XCircle className="h-4 w-4" />
      case 'reopened':
        return <AlertTriangle className="h-4 w-4" />
      default:
        return <AlertCircle className="h-4 w-4" />
    }
  }

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center space-x-4">
          <Button variant="ghost" size="icon">
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <Skeleton className="h-8 w-64 mb-2" />
            <Skeleton className="h-4 w-96" />
          </div>
        </div>
        
        <div className="grid gap-6 md:grid-cols-3">
          {[1, 2, 3].map((i) => (
            <Card key={i}>
              <CardHeader className="pb-2">
                <Skeleton className="h-4 w-20" />
              </CardHeader>
              <CardContent>
                <Skeleton className="h-8 w-12" />
              </CardContent>
            </Card>
          ))}
        </div>

        <div className="grid gap-6">
          <Card>
            <CardHeader>
              <Skeleton className="h-6 w-32" />
            </CardHeader>
            <CardContent>
              <Skeleton className="h-32 w-full" />
            </CardContent>
          </Card>
        </div>
      </div>
    )
  }

  if (!bug) {
    return (
      <div className="text-center py-12">
        <AlertCircle className="mx-auto h-12 w-12 text-gray-400 mb-4" />
        <h3 className="text-lg font-medium text-gray-900 mb-2">缺陷未找到</h3>
        <p className="text-gray-500 mb-4">请检查缺陷ID是否正确</p>
        <Button onClick={() => router.push('/bugs')}>
          <ArrowLeft className="h-4 w-4 mr-2" />
          返回缺陷列表
        </Button>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 页面头部 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <Button variant="ghost" size="icon" onClick={() => router.back()}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <div className="flex items-center space-x-2 mb-2">
              <Badge className={getSeverityColor(bug.severity)}>
                {getSeverityLabel(bug.severity)}
              </Badge>
              <Badge className={getPriorityColor(bug.priority)}>
                {bug.priority}
              </Badge>
              <Badge className={getStatusColor(bug.status)}>
                {getStatusLabel(bug.status)}
              </Badge>
            </div>
            <h1 className="text-3xl font-bold tracking-tight">{bug.title}</h1>
            <div className="flex items-center space-x-4 mt-2 text-sm text-gray-500">
              <span>项目: {bug.project.name} ({bug.project.key})</span>
              {bug.iteration && (
                <span>迭代: {bug.iteration.name}</span>
              )}
              {bug.dueDate && (
                <span className="flex items-center space-x-1">
                  <Calendar className="h-3 w-3" />
                  <span>截止: {new Date(bug.dueDate).toLocaleDateString('zh-CN')}</span>
                </span>
              )}
              {bug.resolvedAt && (
                <span className="flex items-center space-x-1 text-green-600">
                  <CheckCircle className="h-3 w-3" />
                  <span>解决于: {new Date(bug.resolvedAt).toLocaleDateString('zh-CN')}</span>
                </span>
              )}
            </div>
          </div>
        </div>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" size="icon">
              <MoreHorizontal className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem>
              <Edit className="h-4 w-4 mr-2" />
              编辑缺陷
            </DropdownMenuItem>
            <DropdownMenuItem className="text-red-600">
              <Trash2 className="h-4 w-4 mr-2" />
              删除缺陷
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>

      {/* 统计卡片 */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">严重程度</CardTitle>
            <AlertTriangle className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{bug.severity}</div>
            <p className="text-xs text-muted-foreground">
              缺陷严重程度
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">优先级</CardTitle>
            <Bug className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{bug.priority}</div>
            <p className="text-xs text-muted-foreground">
              处理优先级
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">评论</CardTitle>
            <MessageSquare className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{bug._count.comments}</div>
            <p className="text-xs text-muted-foreground">
              评论数量
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">附件</CardTitle>
            <Paperclip className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{bug._count.attachments}</div>
            <p className="text-xs text-muted-foreground">
              附件数量
            </p>
          </CardContent>
        </Card>
      </div>

      {/* 详细信息标签页 */}
      <Tabs defaultValue="details" className="w-full">
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="details">详细信息</TabsTrigger>
          <TabsTrigger value="lifecycle">生命周期</TabsTrigger>
          <TabsTrigger value="comments">评论</TabsTrigger>
          <TabsTrigger value="attachments">附件</TabsTrigger>
        </TabsList>

        <TabsContent value="details" className="space-y-6">
          <div className="grid gap-6 md:grid-cols-2">
            <Card>
              <CardHeader>
                <CardTitle>基本信息</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">严重程度</span>
                  <Badge className={getSeverityColor(bug.severity)}>
                    {getSeverityLabel(bug.severity)}
                  </Badge>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">优先级</span>
                  <Badge className={getPriorityColor(bug.priority)}>
                    {bug.priority}
                  </Badge>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">状态</span>
                  <div className="flex items-center space-x-2">
                    {getStatusIcon(bug.status)}
                    <Badge className={getStatusColor(bug.status)}>
                      {getStatusLabel(bug.status)}
                    </Badge>
                  </div>
                </div>
                {bug.dueDate && (
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium">截止日期</span>
                    <span className="text-sm">
                      {new Date(bug.dueDate).toLocaleDateString('zh-CN')}
                    </span>
                  </div>
                )}
                {bug.resolvedAt && (
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium">解决时间</span>
                    <span className="text-sm text-green-600">
                      {new Date(bug.resolvedAt).toLocaleDateString('zh-CN')}
                    </span>
                  </div>
                )}
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">创建时间</span>
                  <span className="text-sm text-gray-600">
                    {new Date(bug.createdAt).toLocaleDateString('zh-CN')}
                  </span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">更新时间</span>
                  <span className="text-sm text-gray-600">
                    {new Date(bug.updatedAt).toLocaleDateString('zh-CN')}
                  </span>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>关联信息</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">所属项目</span>
                  <Badge variant="outline">{bug.project.name}</Badge>
                </div>
                {bug.iteration && (
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium">所属迭代</span>
                    <Badge variant="outline">{bug.iteration.name}</Badge>
                  </div>
                )}
                {bug.requirement && (
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium">关联需求</span>
                    <div className="flex items-center space-x-2">
                      <span className="text-sm font-medium truncate max-w-[200px]">
                        {bug.requirement.title}
                      </span>
                    </div>
                  </div>
                )}
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">创建者</span>
                  <div className="flex items-center space-x-2">
                    <div className="h-6 w-6 rounded-full bg-gray-300 flex items-center justify-center">
                      <span className="text-xs font-medium text-gray-700">
                        {(bug.creator.name || bug.creator.username || 'U').charAt(0).toUpperCase()}
                      </span>
                    </div>
                    <span className="text-sm">
                      {bug.creator.name || bug.creator.username}
                    </span>
                  </div>
                </div>
                {bug.assignee && (
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium">指派人</span>
                    <div className="flex items-center space-x-2">
                      <div className="h-6 w-6 rounded-full bg-gray-300 flex items-center justify-center">
                        <span className="text-xs font-medium text-gray-700">
                          {(bug.assignee.name || bug.assignee.username || 'U').charAt(0).toUpperCase()}
                        </span>
                      </div>
                      <span className="text-sm">
                        {bug.assignee.name || bug.assignee.username}
                      </span>
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          </div>

          {bug.description && (
            <Card>
              <CardHeader>
                <CardTitle>缺陷描述</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="prose prose-sm max-w-none">
                  <p className="whitespace-pre-wrap">{bug.description}</p>
                </div>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        <TabsContent value="lifecycle" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>缺陷生命周期</CardTitle>
              <CardDescription>
                缺陷的处理过程和时间线
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-6">
                <div className="grid gap-4 md:grid-cols-2">
                  <div className="space-y-4">
                    <div className="flex items-center space-x-3">
                      <div className="h-8 w-8 rounded-full bg-red-100 flex items-center justify-center">
                        <AlertCircle className="h-4 w-4 text-red-600" />
                      </div>
                      <div>
                        <p className="font-medium">缺陷创建</p>
                        <p className="text-sm text-gray-500">
                          {new Date(bug.createdAt).toLocaleDateString('zh-CN')} {new Date(bug.createdAt).toLocaleTimeString('zh-CN')}
                        </p>
                      </div>
                    </div>
                    
                    {bug.dueDate && (
                      <div className="flex items-center space-x-3">
                        <div className="h-8 w-8 rounded-full bg-yellow-100 flex items-center justify-center">
                          <Calendar className="h-4 w-4 text-yellow-600" />
                        </div>
                        <div>
                          <p className="font-medium">截止日期</p>
                          <p className="text-sm text-gray-500">
                            {new Date(bug.dueDate).toLocaleDateString('zh-CN')}
                          </p>
                        </div>
                      </div>
                    )}
                  </div>
                  
                  <div className="space-y-4">
                    {bug.resolvedAt && (
                      <div className="flex items-center space-x-3">
                        <div className="h-8 w-8 rounded-full bg-green-100 flex items-center justify-center">
                          <CheckCircle className="h-4 w-4 text-green-600" />
                        </div>
                        <div>
                          <p className="font-medium">缺陷解决</p>
                          <p className="text-sm text-gray-500">
                            {new Date(bug.resolvedAt).toLocaleDateString('zh-CN')} {new Date(bug.resolvedAt).toLocaleTimeString('zh-CN')}
                          </p>
                        </div>
                      </div>
                    )}
                    
                    <div className="flex items-center space-x-3">
                      <div className="h-8 w-8 rounded-full bg-blue-100 flex items-center justify-center">
                        <Clock className="h-4 w-4 text-blue-600" />
                      </div>
                      <div>
                        <p className="font-medium">最后更新</p>
                        <p className="text-sm text-gray-500">
                          {new Date(bug.updatedAt).toLocaleDateString('zh-CN')} {new Date(bug.updatedAt).toLocaleTimeString('zh-CN')}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="border-t pt-4">
                  <h4 className="font-medium mb-3">当前状态</h4>
                  <div className="flex items-center space-x-3">
                    <div className={`h-10 w-10 rounded-full flex items-center justify-center ${getStatusColor(bug.status).replace('bg-', 'bg-').replace('text-', ' text-')}`}>
                      {getStatusIcon(bug.status)}
                    </div>
                    <div>
                      <p className="font-medium">{getStatusLabel(bug.status)}</p>
                      <p className="text-sm text-gray-500">
                        {bug.status === 'open' && '缺陷已创建，等待处理'}
                        {bug.status === 'in_progress' && '缺陷正在处理中'}
                        {bug.status === 'resolved' && '缺陷已修复，等待验证'}
                        {bug.status === 'closed' && '缺陷已关闭'}
                        {bug.status === 'reopened' && '缺陷已重新打开'}
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="comments" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <MessageSquare className="h-5 w-5" />
                <span>评论</span>
                <Badge variant="secondary">{bug.comments.length}</Badge>
              </CardTitle>
              <CardDescription>
                缺陷的讨论和评论
              </CardDescription>
            </CardHeader>
            <CardContent>
              {bug.comments.length === 0 ? (
                <div className="text-center py-8">
                  <MessageSquare className="mx-auto h-12 w-12 text-gray-400 mb-4" />
                  <p className="text-gray-500">暂无评论</p>
                </div>
              ) : (
                <div className="space-y-4">
                  {bug.comments.map((comment) => (
                    <div key={comment.id} className="p-4 border rounded-lg">
                      <div className="flex items-center justify-between mb-2">
                        <div className="flex items-center space-x-2">
                          <div className="h-6 w-6 rounded-full bg-gray-300 flex items-center justify-center">
                            <span className="text-xs font-medium text-gray-700">
                              {(comment.author.name || comment.author.username || 'U').charAt(0).toUpperCase()}
                            </span>
                          </div>
                          <span className="text-sm font-medium">
                            {comment.author.name || comment.author.username}
                          </span>
                        </div>
                        <span className="text-xs text-gray-500">
                          {new Date(comment.createdAt).toLocaleDateString('zh-CN')} {new Date(comment.createdAt).toLocaleTimeString('zh-CN')}
                        </span>
                      </div>
                      <p className="text-sm text-gray-700 whitespace-pre-wrap">{comment.content}</p>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="attachments" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <Paperclip className="h-5 w-5" />
                <span>附件</span>
                <Badge variant="secondary">{bug.attachments.length}</Badge>
              </CardTitle>
              <CardDescription>
                缺陷的相关附件和文档
              </CardDescription>
            </CardHeader>
            <CardContent>
              {bug.attachments.length === 0 ? (
                <div className="text-center py-8">
                  <Paperclip className="mx-auto h-12 w-12 text-gray-400 mb-4" />
                  <p className="text-gray-500">暂无附件</p>
                </div>
              ) : (
                <div className="space-y-4">
                  {bug.attachments.map((attachment) => (
                    <div key={attachment.id} className="flex items-center justify-between p-4 border rounded-lg">
                      <div className="flex items-center space-x-3">
                        <Paperclip className="h-5 w-5 text-gray-400" />
                        <div>
                          <h4 className="font-medium">{attachment.filename}</h4>
                          <p className="text-sm text-gray-500">
                            {(attachment.size / 1024).toFixed(2)} KB • {attachment.mimeType}
                          </p>
                        </div>
                      </div>
                      <div className="text-right">
                        <p className="text-sm text-gray-500">
                          {new Date(attachment.createdAt).toLocaleDateString('zh-CN')}
                        </p>
                        <Button variant="outline" size="sm" className="mt-1">
                          下载
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}